module buoy_cimiss_xml_mod

  use datetime
  use string
  use container
  use flogger
  use regex
  use fox_sax
  use params_mod
  use data_translators_utils_mod
  use buoy_mod

  implicit none

  private

  public buoy_cimiss_xml_read

  type(hash_table_type), pointer :: dummy_buoys
  type(linked_list_type), pointer :: dummy_records

contains

  subroutine buoy_cimiss_xml_read(file_path, buoys, records, mute)

    character(*), intent(in) :: file_path
    type(hash_table_type), intent(inout), target :: buoys
    type(linked_list_type), intent(inout), target :: records
    logical, intent(in) :: mute

    type(xml_t) xml
    integer i, iostat

    dummy_buoys => buoys
    dummy_records => records

    if (mute) call log_notice('Reading ' // trim(file_path) // ' ...')

    call open_xml_file(xml, file_path, iostat)

    call parse(xml, startElement_handler=startElement_handler)

    call stop_parser(xml)

    call close_xml_t(xml)

    if (mute) call log_notice('Buoy size is ' // trim(to_str(buoys%size)) // ', record size is ' // trim(to_str(records%size)) // '.')

  end subroutine buoy_cimiss_xml_read

  subroutine startElement_handler(uri, local_name, name, attributes)

    character(*), intent(in) :: uri
    character(*), intent(in) :: local_name
    character(*), intent(in) :: name
    type(dictionary_t), intent(in) :: attributes

    type(reg_matches), allocatable :: res(:)
    type(buoy_type), pointer :: buoy
    type(buoy_record_type), pointer :: record
    character(10) buoy_name
    character(256) value
    real lat, lon, z
    integer year, month, day, hour, minute
    type(datetime_type) time
    real ta, ta_qc
    real td, td_qc
    real rh, rh_qc
    real p, p_qc
    real sst, sst_qc
    real wd, wd_qc
    real ws, ws_qc
    real hww, hww_qc
    real pww, pww_qc
    real hsw, svh_qc
    real psw, psw_qc
    real dsw, dsw_qc
    real vis, vis_qc
    real clc, clc_qc
    integer i

    select case (name)
    case ('DS')
      do i = 1, getLength(attributes)
        select case (getQName(attributes, i))
        case ('requestParams')
          res = regex_search(getValue(attributes, i), 'datacode=([^&]*)&?')
          if (size(res) == 1) then
            if (res(1)%match(2)%str == 'OCEN_CHN_BUOY') exit
          end if
          call log_error('Input file is not CIMISS OCEN_CHN_BUOY!')
        end select
      end do
    case ('R')
      do i = 1, getLength(attributes)
        value = getValue(attributes, i)
        select case (getQName(attributes, i))
        case ('Station_Id_C')
          buoy_name = value
        case ('Lat')
          read(value, *) lat
        case ('Lon')
          read(value, *) lon
        case ('Alti')
          read(value, *) z
        case ('Year')
          read(value, *) year
        case ('Mon')
          read(value, *) month
        case ('Day')
          read(value, *) day
        case ('Hour')
          read(value, *) hour
        case ('Min')
          read(value, *) minute
        case ('TEM')
          read(value, *) ta
        case ('Q_TEM')
          read(value, *) ta_qc
        case ('RHU')
          read(value, *) rh
        case ('Q_RHU')
          read(value, *) rh_qc
        case ('PRS')
          read(value, *) p
        case ('Q_PRS')
          read(value, *) p_qc
        case ('SST')
          read(value, *) sst
        case ('Q_SST')
          read(value, *) sst_qc
        case ('WIN_D_Avg_10mi')
          read(value, *) wd
        case ('Q_WIN_D_Avg_10mi')
          read(value, *) wd_qc
        case ('WIN_S_Avg_10mi')
          read(value, *) ws
        case ('Q_WIN_S_Avg_10mi')
          read(value, *) ws_qc
        end select
      end do
      call time%init(year, month, day, hour, minute)
      lon = merge(real_missing_value, lon, is_missing(lon, src='cimiss'))
      lat = merge(real_missing_value, lat, is_missing(lat, src='cimiss'))
      z   = merge(real_missing_value, z,   is_missing(z,   src='cimiss'))
      ta  = merge(real_missing_value, ta,  is_missing(ta,  src='cimiss'))
      rh  = merge(real_missing_value, rh,  is_missing(rh,  src='cimiss'))
      p   = merge(real_missing_value, p,   is_missing(p,   src='cimiss'))
      sst = merge(real_missing_value, sst, is_missing(sst, src='cimiss'))
      wd  = merge(real_missing_value, wd,  is_missing(wd,  src='cimiss'))
      ws  = merge(real_missing_value, ws,  is_missing(ws,  src='cimiss'))

      ! FIXME: CIMISS temperature units may be Kelvin!
      if (.not. is_missing(ta) .and. ta > 200) then
        ta = ta - freezing_point
        if (ta > 100) then
          call log_warning('Bad temperature value ' // to_str(ta, 10) // 'for ' // trim(buoy_name) // '!')
          ta = real_missing_value
        else
          call log_warning('Convert temperature units from K to degC for ' // trim(buoy_name) // '.')
        end if
      end if
      ! Create buoy and record.
      if (dummy_buoys%hashed(buoy_name)) then
        select type (value => dummy_buoys%value(buoy_name))
        type is (buoy_type)
          buoy => value
        end select
      else
        allocate(buoy)
        call buoy%init(buoy_name)
        buoy%seq_id = dummy_buoys%size
        call dummy_buoys%insert(buoy_name, buoy)
      end if
      allocate(record)
      record%seq_id = dummy_records%size
      record%buoy => buoy
      record%time = time
      ! Set record.
      record%source = 'CIMISS'
      record%lon = lon
      record%lat = lat
      record%z   = z
      record%p   = p
      record%ta  = ta
      record%sst = sst
      record%rh  = rh
      record%td  = dewpoint_from_relative_humidity(ta, rh)
      record%wd  = wd
      record%ws  = ws
      record%ua  = wind_u_component(ws, wd)
      record%va  = wind_v_component(ws, wd)
      ! TODO: How to map CIMISS QC to PrepBUFR QC?
      record%ta_qc  = ta_qc
      record%sst_qc = sst_qc
      record%td_qc  = td_qc
      record%rh_qc  = rh_qc
      record%p_qc   = p_qc
      record%wd_qc  = wd_qc
      record%ws_qc  = ws_qc
      call dummy_records%insert(buoy_name // '@' // time%isoformat(), record)
      call buoy%records%insert(trim(to_str(record%seq_id)), record, nodup=.true.)
    end select

  end subroutine startElement_handler

end module buoy_cimiss_xml_mod
